//https://leetcode.cn/problems/last-stone-weight-ii/

class Solution {
public:
    int lastStoneWeightII(vector<int>& stones) {
        int n = stones.size(), sum = 0;
        for(auto num : stones)
        {
            sum += num;
        }
        int tar = sum / 2;
        vector<vector<int>> dp(n + 1, vector<int>(tar + 1));
        
        for(int i = 1; i <= n; i++)
        {
            for(int j = 0; j <= tar; j++)
            {
                dp[i][j] = dp[i - 1][j];
                if(j >= stones[i - 1])
                    dp[i][j] = max(dp[i][j], dp[i - 1][j - stones[i - 1]] + stones[i - 1]);
            }
        }
        return sum - 2 * dp[n][tar];
    }
};